package thoven.achievement.net.jsonutil.action

import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.ui.Messages
import thoven.achievement.net.jsonutil.service.JsonCleaner

/**
 * 转义 JSON 字符串的编辑器操作
 */
class EscapeJsonAction : AnAction() {
    
    override fun actionPerformed(e: AnActionEvent) {
        val editor = e.getData(CommonDataKeys.EDITOR) ?: return
        val project = e.project ?: return
        val document = editor.document
        
        val selectionModel = editor.selectionModel
        val selectedText = selectionModel.selectedText
        
        if (selectedText.isNullOrBlank()) {
            Messages.showWarningDialog(
                project,
                "请选择要转义的 JSON 文本",
                "JSON 转义"
            )
            return
        }
        
        val escaped = JsonCleaner.escapeJson(selectedText)
        
        WriteCommandAction.runWriteCommandAction(project) {
            document.replaceString(
                selectionModel.selectionStart,
                selectionModel.selectionEnd,
                escaped
            )
        }
    }
    
    override fun update(e: AnActionEvent) {
        val editor = e.getData(CommonDataKeys.EDITOR)
        val hasSelection = editor?.selectionModel?.hasSelection() == true
        e.presentation.isEnabledAndVisible = hasSelection
    }
}

